package com.yusheng.tr.multi.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yusheng.domain.R;
import com.yusheng.exceptions.ServiceException;
import com.yusheng.tr.common.core.page.PageParam;
import com.yusheng.tr.common.core.utils.minio.MinioUtils;
import com.yusheng.tr.common.core.utils.minio.ObjectItem;
import com.yusheng.tr.common.core.entity.multi.EndOfLifeMaterialsEntity;
import com.yusheng.tr.multi.service.IEndOfLifeMaterialsService;
import com.yusheng.tr.multi.service.impl.CommonExcelListener;
import com.yusheng.tr.multi.service.impl.StmtMngServiceImpl;
import com.yusheng.utils.CommonExcelVo;
import com.yusheng.utils.FilePathUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/end/of/life/materials")
@Tag(name = "报废物资管理")
public class EndOfLifeMaterialsController {

    @Autowired
    private IEndOfLifeMaterialsService materialsService;

    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("/page/list")
    @Operation(summary = "分页条件查询",description = "分页条件查询")
    @Parameter(name = "dto",description = "分页条件查询")
    public R<PageInfo<EndOfLifeMaterialsEntity>> pageInfo(@RequestBody PageParam<EndOfLifeMaterialsEntity> dto){
        PageInfo<EndOfLifeMaterialsEntity> pageInfo = PageHelper.startPage(dto.getPageNum(),dto.getPageSize())
                .doSelectPageInfo(() -> materialsService.list(
                        new LambdaQueryWrapper<EndOfLifeMaterialsEntity>()
                                .eq(EndOfLifeMaterialsEntity::getMaterialsType,dto.getParam().getMaterialsType())
                                .eq(StringUtils.isNotEmpty(dto.getParam().getProductSpecification()),EndOfLifeMaterialsEntity::getProductSpecification,dto.getParam().getProductSpecification())
                ));
        return R.ok(pageInfo);
    }


    @GetMapping("/upload/{materialsType}")
    @Operation(summary = "上传物资或电缆excel表")
    @Parameter(name = "materialsType",description = "材料类型")
    public R<ObjectItem> upload(@PathVariable Integer materialsType) throws Exception{
        String outPath;
        if (materialsType == 0){
            outPath = FilePathUtils.getTemplatePath("\\templete\\materials\\", "物资.xlsx");
        }else {
            outPath = FilePathUtils.getTemplatePath("\\templete\\materials\\", "电缆.xlsx");
        }
        return R.ok(minioUtils.uploadFile(StmtMngServiceImpl.getMulFileByPath(outPath), "test"));
    }

    @PostMapping("/import/excel")
    @Operation(summary = "导入物资或者是电缆的excel表")
    @Parameters({@Parameter(name = "file",description = "上传的文件"),
            @Parameter(name = "materialsType",description = "材料类型")
    })
    public R<?> importExcel(MultipartFile file,Integer materialsType) throws Exception{
        String fileName = file.getOriginalFilename();
        CommonExcelListener listener = new CommonExcelListener();
        ExcelReader reader = EasyExcel.read(file.getInputStream(), CommonExcelVo.class, listener).build();
        reader.readAll();
        reader.finish();
        assert fileName != null;
        fileName = fileName.split("\\.")[0];
        List<CommonExcelVo> commonExcelVos = listener.finalAll();
        if (CollectionUtils.isEmpty(commonExcelVos)){
            throw new ServiceException("数据为空" + "\uD83D\uDE01");
        }
        List<EndOfLifeMaterialsEntity> list = new ArrayList<>();
        commonExcelVos.forEach(cl ->{
            EndOfLifeMaterialsEntity entity = new EndOfLifeMaterialsEntity();
            entity.setMaterialsType(materialsType);
            if (materialsType == 0){
                entity.setItemGroup(cl.getA());
                entity.setCode(cl.getB());
                entity.setProductSpecification(cl.getC());
                entity.setUnitCode(cl.getD());
                entity.setAllTotal(cl.getE());
                entity.setSaveAddress(cl.getF());
                entity.setScrapReason(cl.getG());
                entity.setSysDepartName(cl.getH());
                entity.setCreateTime(new Date());
            }else {
                entity.setBeforeCode(cl.getA());
                entity.setAfterCode(cl.getB());
                entity.setProductSpecification(cl.getC());
                entity.setItemGroup(cl.getD());
                entity.setCarCode(cl.getE());
                entity.setBeforeLength(cl.getF());
                entity.setAfterLength(cl.getG());
                entity.setScrapPeople(cl.getH());
                entity.setSaveAddress(cl.getI());
                entity.setScrapReason(cl.getJ());
                entity.setRemark(cl.getK());
                entity.setCreateTime(new Date());
            }
            list.add(entity);
        });
        materialsService.saveOrUpdateBatch(list);
        return R.ok();
    }
}
